package hibernate.dao;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import hibernate.entity.Usuario;

import java.util.List;

public class UsuarioDAO {

	private Session session;

	public UsuarioDAO(){

	}

	public void adiciona(Usuario usuario){		

		HibernateConnection.buildSessionFactory();
		session = HibernateConnection.openSession();		
		Transaction transaction = session.beginTransaction();

		try{
			session.save(usuario);
			transaction.commit();
		} catch(Exception e){
			if(transaction != null)
				transaction.rollback();
			System.out.println("Erro: " + e);
		} finally {
			HibernateConnection.closeSessionFactory();
			session.clear();
			session.close();
		}			
	}	

	public void altera(Usuario usuario){		

		HibernateConnection.buildSessionFactory();
		session = HibernateConnection.openSession();		
		Transaction transaction = session.beginTransaction();

		try{
			session.update(usuario);
			transaction.commit();
		} catch(Exception e){
			if(transaction != null)
				transaction.rollback();
			System.out.println("Erro: " + e);
		} finally {
			HibernateConnection.closeSessionFactory();
			session.clear();
			session.close();
		}
	}	

	public void remove(Usuario usuario){

		HibernateConnection.buildSessionFactory();
		session = HibernateConnection.openSession();		
		Transaction transaction = session.beginTransaction();

		try{
			session.delete(usuario);
			transaction.commit();
		} catch(Exception e){
			if(transaction != null)
				transaction.rollback();
			System.out.println("Erro: " + e);
		} finally {
			HibernateConnection.closeSessionFactory();
			session.clear();
			session.close();
		}
	}	

	public Usuario importaDados(String login){

		HibernateConnection.buildSessionFactory();
		session = HibernateConnection.openSession();			
		Criteria criteria = session.createCriteria(Usuario.class);
		Usuario usuario = null;

		try{
			criteria.add(Restrictions.eq("login", login));
			criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
			usuario = (Usuario) criteria.uniqueResult();
		} catch(Exception e){
			System.out.println("Erro: " + e);
		} finally {
			HibernateConnection.closeSessionFactory();
			session.clear();
			session.close();
		}			

		return usuario;
	}

	public List<Usuario> getLista(){

		HibernateConnection.buildSessionFactory();
		session = HibernateConnection.openSession();			
		Criteria criteria = session.createCriteria(Usuario.class);		
		List<Usuario> listaUsuarios = null;

		try{
			listaUsuarios = (List<Usuario>) criteria.list();
		} catch(Exception e){
			System.out.println("Erro: " + e);
		} finally {
			HibernateConnection.closeSessionFactory();
			session.clear();
			session.close();
		}			
		return listaUsuarios;
	}
}

